const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// 数据库连接配置
const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '123456', // 请根据实际情况修改
    database: 'gamebag',
    multipleStatements: true
};

// 通用获取数据库连接
async function getConn() {
    return await mysql.createConnection(dbConfig);
}

// 技能目标类型白名单
const skillTargetType = {
    1: 'monster', // 火球术
    2: 'self',    // 治疗术
    3: 'self',    // 防御姿态（被动）
    4: 'monster', // 冰锥术
    5: 'monster', // 剑气斩
    6: 'all',     // 神圣祈祷
    7: 'self'     // 闪避（被动）
};

// 示例API: 获取所有物品
app.get('/api/items', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute('SELECT * FROM items');
    await conn.end();
    res.json(rows);
});

// 示例API: 获取所有技能
app.get('/api/skills', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute('SELECT * FROM skills');
    await conn.end();
    res.json(rows);
});

// 示例API: 获取所有小怪
app.get('/api/monsters', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute('SELECT * FROM monsters');
    await conn.end();
    res.json(rows);
});

// 示例API: 获取所有Boss
app.get('/api/bosses', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute('SELECT * FROM bosses');
    await conn.end();
    res.json(rows);
});

// 获取所有角色
app.get('/api/characters', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute('SELECT * FROM characters');
    await conn.end();
    res.json(rows);
});

// 示例API: 获取角色信息
app.get('/api/characters/:id', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    await conn.end();
    res.json(rows[0] || null);
});

// 回合制自动战斗
app.post('/api/characters/:id/fight', async (req, res) => {
    const { monsterId } = req.body;
    const conn = await getConn();
    // 获取角色
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    if (!charRows.length) return res.status(404).json({ error: '角色不存在' });
    let character = charRows[0];
    // 获取角色装备加成
    const [equipRows] = await conn.execute('SELECT i.attack_bonus, i.defense_bonus, i.hp_bonus FROM character_equipments ce LEFT JOIN items i ON ce.item_id = i.id WHERE ce.character_id=?', [character.id]);
    let equip_bonus = { atk: 0, def: 0, hp: 0 };
    for (const row of equipRows) {
        if (!row) continue;
        equip_bonus.atk += row.attack_bonus || 0;
        equip_bonus.def += row.defense_bonus || 0;
        equip_bonus.hp += row.hp_bonus || 0;
    }
    // 获取被动技能加成
    const [passiveSkills] = await conn.execute('SELECT s.effect FROM character_skills cs JOIN skills s ON cs.skill_id = s.id WHERE cs.character_id=? AND s.type="被动"', [character.id]);
    let skill_bonus = { atk: 0, def: 0, hp: 0, dodge: 0 };
    for (const row of passiveSkills) {
        if (!row || !row.effect) continue;
        let effect = {};
        try { effect = JSON.parse(row.effect); } catch { }
        if (effect.def_up) skill_bonus.def += effect.def_up;
        if (effect.hp_up) skill_bonus.hp += effect.hp_up;
        if (effect.atk_up) skill_bonus.atk += effect.atk_up;
        if (effect.dodge_up) skill_bonus.dodge += effect.dodge_up;
    }
    // 角色最终属性
    let role = {
        hp: character.hp + equip_bonus.hp + skill_bonus.hp,
        atk: character.atk + equip_bonus.atk + skill_bonus.atk,
        def: character.def + equip_bonus.def + skill_bonus.def,
        dodge: skill_bonus.dodge
    };
    // 获取怪物
    const [monsterRows] = await conn.execute('SELECT * FROM monsters WHERE id=?', [monsterId]);
    if (!monsterRows.length) return res.status(404).json({ error: '怪物不存在' });
    let monster = {
        name: monsterRows[0].name,
        hp: monsterRows[0].hp,
        atk: monsterRows[0].atk,
        def: monsterRows[0].def
    };
    // 回合制战斗
    let rounds = [];
    let turn = 1;
    let roleHp = role.hp;
    let monsterHp = monster.hp;
    while (roleHp > 0 && monsterHp > 0) {
        // 角色攻击怪物
        let dmgToMonster = Math.max(1, role.atk - monster.def);
        monsterHp -= dmgToMonster;
        rounds.push({
            turn, attacker: '角色', damage: dmgToMonster, target: '怪物', monsterHp: Math.max(monsterHp, 0), roleHp: Math.max(roleHp, 0),
            roleAtk: role.atk, monsterDef: monster.def, roleDef: role.def, monsterAtk: monster.atk, skill_bonus
        });
        if (monsterHp <= 0) break;
        // 怪物攻击角色
        let dmgToRole = Math.max(1, monster.atk - role.def);
        roleHp -= dmgToRole;
        rounds.push({
            turn, attacker: '怪物', damage: dmgToRole, target: '角色', monsterHp: Math.max(monsterHp, 0), roleHp: Math.max(roleHp, 0),
            roleAtk: role.atk, monsterDef: monster.def, roleDef: role.def, monsterAtk: monster.atk, skill_bonus
        });
        turn++;
    }
    let win = roleHp > 0;
    let expGain = 0, coinGain = 0, dropItems = [], levelUp = false, newLevel = character.level;
    if (win) {
        // 经验结算
        expGain = (monster.hp || 0) + (monster.atk || 0) + (monster.def || 0);
        let newExp = (character.exp || 0) + expGain;
        // 角色最大生命（基础+装备+被动）
        let maxHp = character.hp + equip_bonus.hp + skill_bonus.hp;
        let newHp = Math.max(0, Math.min(roleHp - equip_bonus.hp, maxHp)); // 不能高于最大生命，不能为负
        let newMp = character.mp;
        let newAtk = character.atk;
        let newDef = character.def;
        // 升级规则
        let candidateSkills = [];
        const [learnedRows] = await conn.execute('SELECT skill_id FROM character_skills WHERE character_id=?', [character.id]);
        const learned = learnedRows.map(r => r.skill_id);
        while (newExp >= 100 * newLevel) {
            newExp -= 100 * newLevel;
            newLevel++;
            newHp += 20;
            newMp += 10;
            newAtk += 2;
            newDef += 2;
            levelUp = true;
            const [allSkills] = await conn.execute('SELECT * FROM skills');
            const unlearned = allSkills.filter(s => !learned.includes(s.id));
            if (unlearned.length > 0) {
                const shuffled = unlearned.sort(() => 0.5 - Math.random());
                candidateSkills = shuffled.slice(0, 3).map(s => ({ id: s.id, name: s.name, desc: s.desc, type: s.type }));
                break;
            }
        }
        // 怪物掉落
        let drops = [];
        try { drops = JSON.parse(monsterRows[0].drops || '[]'); } catch { }
        for (const drop of drops) {
            let dropProb = drop.prob || 1;
            const [itemRows] = await conn.execute('SELECT * FROM items WHERE id=?', [drop.itemId]);
            if (itemRows.length) {
                const rarity = itemRows[0].rarity || 1;
                if (rarity >= 3) dropProb = 0.05;
                if (Math.random() < dropProb) {
                    dropItems.push({ id: drop.itemId, name: itemRows[0].name, qty: (drop.qty || 1), rarity });
                    const [envRows] = await conn.execute('SELECT * FROM env_items WHERE character_id=? AND item_id=?', [character.id, drop.itemId]);
                    if (envRows.length) {
                        await conn.execute('UPDATE env_items SET qty=qty+? WHERE id=?', [drop.qty || 1, envRows[0].id]);
                    } else {
                        await conn.execute('INSERT INTO env_items (character_id, item_id, qty) VALUES (?, ?, ?)', [character.id, drop.itemId, drop.qty || 1]);
                    }
                }
            }
        }
        // 若无掉落则随机掉落1-2个物品
        if (dropItems.length === 0) {
            const [allItems] = await conn.execute('SELECT * FROM items');
            const shuffled = allItems.sort(() => 0.5 - Math.random());
            const dropCount = Math.floor(Math.random() * 2) + 1; // 1-2个
            for (let i = 0; i < dropCount && i < shuffled.length; i++) {
                const item = shuffled[i];
                dropItems.push({ id: item.id, name: item.name, qty: 1, rarity: item.rarity });
                const [envRows] = await conn.execute('SELECT * FROM env_items WHERE character_id=? AND item_id=?', [character.id, item.id]);
                if (envRows.length) {
                    await conn.execute('UPDATE env_items SET qty=qty+1 WHERE id=?', [envRows[0].id]);
                } else {
                    await conn.execute('INSERT INTO env_items (character_id, item_id, qty) VALUES (?, ?, 1)', [character.id, item.id]);
                }
            }
        }
        // 金币掉落
        coinGain = Math.floor(Math.random() * 41) + 10;
        let newCoin = (character.coin || 0) + coinGain;
        // 怪物被打败后自动刷新新怪物或Boss
        let newMonster = null;
        const rand = Math.random();
        if (rand < 0.3) {
            const [allBosses] = await conn.execute('SELECT * FROM bosses');
            if (allBosses.length > 0) {
                const randIdx = Math.floor(Math.random() * allBosses.length);
                const boss = allBosses[randIdx];
                newMonster = {
                    id: boss.id,
                    name: boss.name,
                    hp: boss.hp,
                    atk: boss.atk,
                    def: boss.def,
                    desc: boss.desc,
                    isBoss: true
                };
            }
        } else {
            const [allMonsters] = await conn.execute('SELECT * FROM monsters');
            if (allMonsters.length > 0) {
                const randIdx = Math.floor(Math.random() * allMonsters.length);
                const monster = allMonsters[randIdx];
                newMonster = {
                    id: monster.id,
                    name: monster.name,
                    hp: monster.hp,
                    atk: monster.atk,
                    def: monster.def,
                    desc: monster.desc,
                    isBoss: false
                };
            }
        }
        await conn.execute('UPDATE characters SET exp=?, level=?, hp=?, mp=?, atk=?, def=?, coin=? WHERE id=?', [newExp, newLevel, newHp, newMp, newAtk, newDef, newCoin, character.id]);
        await conn.end();
        return res.json({ win, rounds, expGain, coinGain, newExp, newLevel, levelUp, dropItems, hp: newHp, isDead: newHp <= 0, candidateSkills, newMonster });
    } else {
        // 失败只扣血
        let newHp = Math.max(0, roleHp - equip_bonus.hp);
        await conn.execute('UPDATE characters SET hp=? WHERE id=?', [newHp, character.id]);
        await conn.end();
        return res.json({ win, rounds, expGain: 0, coinGain: 0, newExp: character.exp, newLevel: character.level, levelUp: false, dropItems: [], hp: newHp, isDead: newHp <= 0 });
    }
});

// 角色学习技能
app.post('/api/characters/:id/learn-skill', async (req, res) => {
    const { skillId } = req.body;
    const conn = await getConn();
    // 检查是否已学
    const [existRows] = await conn.execute('SELECT * FROM character_skills WHERE character_id=? AND skill_id=?', [req.params.id, skillId]);
    if (existRows.length) { await conn.end(); return res.json({ learned: true }); }
    await conn.execute('INSERT INTO character_skills (character_id, skill_id) VALUES (?, ?)', [req.params.id, skillId]);
    await conn.end();
    res.json({ learned: true });
});

// 获取角色已学技能详情
app.get('/api/characters/:id/skills', async (req, res) => {
    const conn = await getConn();
    const [skills] = await conn.execute('SELECT s.* FROM character_skills cs JOIN skills s ON cs.skill_id = s.id WHERE cs.character_id=?', [req.params.id]);
    await conn.end();
    res.json(skills);
});

// 获取角色背包物品
app.get('/api/characters/:id/bag', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute(`
    SELECT b.id as bag_id, i.id as item_id, i.name, i.desc, i.type, i.rarity, b.qty
    FROM bags b
    JOIN items i ON b.item_id = i.id
    WHERE b.character_id = ?
  `, [req.params.id]);
    await conn.end();
    res.json(rows);
});

// 添加物品到背包
app.post('/api/characters/:id/bag/add', async (req, res) => {
    const { itemId, qty } = req.body;
    const conn = await getConn();
    // 检查是否已有该物品
    const [existRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (existRows.length) {
        await conn.execute('UPDATE bags SET qty=qty+? WHERE id=?', [qty, existRows[0].id]);
    } else {
        await conn.execute('INSERT INTO bags (character_id, item_id, qty) VALUES (?, ?, ?)', [req.params.id, itemId, qty]);
    }
    await conn.end();
    res.json({ success: true });
});

// 移除背包物品
app.post('/api/characters/:id/bag/remove', async (req, res) => {
    const { itemId, qty } = req.body;
    const conn = await getConn();
    const [existRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (!existRows.length) return res.status(404).json({ error: '物品不存在' });
    if (existRows[0].qty > qty) {
        await conn.execute('UPDATE bags SET qty=qty-? WHERE id=?', [qty, existRows[0].id]);
    } else {
        await conn.execute('DELETE FROM bags WHERE id=?', [existRows[0].id]);
    }
    await conn.end();
    res.json({ success: true });
});

// 角色释放技能
app.post('/api/characters/:id/use-skill', async (req, res) => {
    const { skillId, monsterId, target } = req.body; // target: 'monster' or 'self' or 'all'
    const conn = await getConn();
    // 获取角色
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    if (!charRows.length) return res.status(404).json({ error: '角色不存在' });
    let character = charRows[0];
    // 校验是否已学该技能
    const [learnedRows] = await conn.execute('SELECT * FROM character_skills WHERE character_id=? AND skill_id=?', [req.params.id, skillId]);
    if (!learnedRows.length) { await conn.end(); return res.status(403).json({ error: '未学会该技能' }); }
    // 获取技能
    const [skillRows] = await conn.execute('SELECT * FROM skills WHERE id=?', [skillId]);
    if (!skillRows.length) return res.status(404).json({ error: '技能不存在' });
    const skill = skillRows[0];
    // 校验目标类型
    const expectTarget = skillTargetType[skillId] || 'self';
    if (expectTarget === 'self' && target !== 'self') { await conn.end(); return res.status(400).json({ error: '该技能只能对自己使用' }); }
    if (expectTarget === 'monster' && target !== 'monster') { await conn.end(); return res.status(400).json({ error: '该技能只能对怪物使用' }); }
    if (expectTarget === 'all' && target !== 'all') { await conn.end(); return res.status(400).json({ error: '该技能只能对全体使用' }); }
    // 检查蓝量
    if (character.mp < skill.mp_cost) return res.status(400).json({ error: '蓝量不足' });
    let result = { type: skill.type, mpCost: skill.mp_cost, skillName: skill.name };
    let updateChar = false;
    // 技能释放接口内，主动技能处理部分：
    if (skill.type === '主动') {
        if (expectTarget === 'monster') {
            // 获取怪物
            const [monsterRows] = await conn.execute('SELECT * FROM monsters WHERE id=?', [monsterId]);
            if (!monsterRows.length) return res.status(404).json({ error: '怪物不存在' });
            let monster = monsterRows[0];
            let effect = {};
            try { effect = JSON.parse(skill.effect || '{}'); } catch { }
            let damage = effect.damage || 0;
            let newHp = Math.max(0, monster.hp - damage);
            await conn.execute('UPDATE monsters SET hp=? WHERE id=?', [newHp, monsterId]);
            result.target = 'monster';
            result.damage = damage;
            result.monsterHp = newHp;
            result.monsterName = monster.name;
        }
        // 治疗技能支持百分比
        let effect = {};
        try { effect = JSON.parse(skill.effect || '{}'); } catch { }
        let heal = 0;
        let maxHp = 1000; // 默认最大生命
        if (effect.heal_percent) {
            // 计算最大生命（基础+等级成长+装备+被动）
            const [equipRows] = await conn.execute('SELECT i.hp_bonus FROM character_equipments ce LEFT JOIN items i ON ce.item_id = i.id WHERE ce.character_id=?', [character.id]);
            let equipHp = 0;
            for (const row of equipRows) { if (row && row.hp_bonus) equipHp += row.hp_bonus; }
            const [passiveSkills] = await conn.execute('SELECT s.effect FROM character_skills cs JOIN skills s ON cs.skill_id = s.id WHERE cs.character_id=? AND s.type="被动"', [character.id]);
            let skillHp = 0;
            for (const row of passiveSkills) {
                if (!row || !row.effect) continue;
                let eff = {};
                try { eff = JSON.parse(row.effect); } catch { }
                if (eff.hp_up) skillHp += eff.hp_up;
            }
            maxHp = (100 + (character.level - 1) * 20) + equipHp + skillHp;
            heal = Math.floor(maxHp * effect.heal_percent);
        } else if (effect.heal) {
            heal = effect.heal;
        }
        let newHp = Math.min(character.hp + heal, maxHp);
        await conn.execute('UPDATE characters SET hp=? WHERE id=?', [newHp, character.id]);
        result.target = 'self';
        result.heal = heal;
        result.newHp = newHp;
        updateChar = true;
    } else if (expectTarget === 'all') {
        // 群体治疗（全体角色）
        let effect = {};
        try { effect = JSON.parse(skill.effect || '{}'); } catch { }
        let heal = effect.heal || 0;
        // 查询所有角色
        const [allChars] = await conn.execute('SELECT * FROM characters');
        let healed = [];
        for (const c of allChars) {
            let newHp = c.hp + heal;
            await conn.execute('UPDATE characters SET hp=? WHERE id=?', [newHp, c.id]);
            healed.push({ id: c.id, name: c.name, heal, newHp });
        }
        result.target = 'all';
        result.heal = heal;
        result.healed = healed;
        updateChar = true;
    }
    // 被动技能等可扩展
    // 扣除蓝量
    let newMp = character.mp - skill.mp_cost;
    await conn.execute('UPDATE characters SET mp=? WHERE id=?', [newMp, character.id]);
    if (updateChar) character.hp = result.newHp;
    character.mp = newMp;
    await conn.end();
    res.json({ result, character });
});

// 获取角色装备栏
app.get('/api/characters/:id/equipments', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute(`
    SELECT ce.slot, ce.item_id, i.name, i.desc, i.type, i.rarity, i.attack_bonus, i.defense_bonus, i.hp_bonus, i.extra
    FROM character_equipments ce
    LEFT JOIN items i ON ce.item_id = i.id
    WHERE ce.character_id = ?
    ORDER BY ce.slot
  `, [req.params.id]);
    await conn.end();
    res.json(rows);
});

// 获取角色属性（含装备加成、被动技能加成）
app.get('/api/characters/:id/attributes', async (req, res) => {
    const conn = await getConn();
    // 获取角色基础属性
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    if (!charRows.length) return res.status(404).json({ error: '角色不存在' });
    const base = {
        hp: charRows[0].hp,
        mp: charRows[0].mp,
        atk: charRows[0].atk,
        def: charRows[0].def
    };
    // 获取装备加成
    const [equipRows] = await conn.execute('SELECT i.attack_bonus, i.defense_bonus, i.hp_bonus FROM character_equipments ce LEFT JOIN items i ON ce.item_id = i.id WHERE ce.character_id=?', [req.params.id]);
    let equip_bonus = { atk: 0, def: 0, hp: 0 };
    for (const row of equipRows) {
        if (!row) continue;
        equip_bonus.atk += row.attack_bonus || 0;
        equip_bonus.def += row.defense_bonus || 0;
        equip_bonus.hp += row.hp_bonus || 0;
    }
    // 获取被动技能加成
    const [passiveSkills] = await conn.execute('SELECT s.effect FROM character_skills cs JOIN skills s ON cs.skill_id = s.id WHERE cs.character_id=? AND s.type="被动"', [req.params.id]);
    let skill_bonus = { atk: 0, def: 0, hp: 0, dodge: 0 };
    for (const row of passiveSkills) {
        if (!row || !row.effect) continue;
        let effect = {};
        try { effect = JSON.parse(row.effect); } catch { }
        if (effect.def_up) skill_bonus.def += effect.def_up;
        if (effect.hp_up) skill_bonus.hp += effect.hp_up;
        if (effect.atk_up) skill_bonus.atk += effect.atk_up;
        if (effect.dodge_up) skill_bonus.dodge += effect.dodge_up;
    }
    // 计算最终属性
    const final = {
        hp: base.hp + equip_bonus.hp + skill_bonus.hp,
        mp: base.mp,
        atk: base.atk + equip_bonus.atk + skill_bonus.atk,
        def: base.def + equip_bonus.def + skill_bonus.def,
        dodge: skill_bonus.dodge
    };
    await conn.end();
    res.json({ base, equip_bonus, skill_bonus, final });
});

// 穿戴装备
app.post('/api/characters/:id/equip', async (req, res) => {
    const { slot, itemId } = req.body;
    const conn = await getConn();
    // 检查背包是否有该物品
    const [bagRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (!bagRows.length || bagRows[0].qty < 1) { await conn.end(); return res.status(400).json({ error: '背包中无此装备' }); }
    // 获取物品类型
    const [itemRows] = await conn.execute('SELECT * FROM items WHERE id=?', [itemId]);
    if (!itemRows.length) { await conn.end(); return res.status(404).json({ error: '物品不存在' }); }
    const item = itemRows[0];
    // 类型与槽位强校验
    if ((slot === 'weapon' && item.type !== '武器') ||
        (slot === 'armor' && item.type !== '防具') ||
        (slot === 'accessory' && item.type !== '饰品') ||
        (slot === 'shoes' && item.type !== '鞋子')) {
        await conn.end();
        return res.status(400).json({ error: '装备类型与槽位不符' });
    }
    // 检查装备栏是否有该slot，没有则插入
    const [equipRows] = await conn.execute('SELECT * FROM character_equipments WHERE character_id=? AND slot=?', [req.params.id, slot]);
    let oldItemId = equipRows.length ? equipRows[0].item_id : null;
    if (!equipRows.length) {
        await conn.execute('INSERT INTO character_equipments (character_id, slot, item_id) VALUES (?, ?, NULL)', [req.params.id, slot]);
    }
    // 更新装备栏
    await conn.execute('UPDATE character_equipments SET item_id=? WHERE character_id=? AND slot=?', [itemId, req.params.id, slot]);
    // 背包减1，若为0则删除
    await conn.execute('UPDATE bags SET qty=qty-1 WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    const [afterRows] = await conn.execute('SELECT qty FROM bags WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (afterRows.length && afterRows[0].qty <= 0) {
        await conn.execute('DELETE FROM bags WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    }
    // 如果原装备存在，回到背包
    if (oldItemId) {
        const [oldBag] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, oldItemId]);
        if (oldBag.length) {
            await conn.execute('UPDATE bags SET qty=qty+1 WHERE id=?', [oldBag[0].id]);
        } else {
            await conn.execute('INSERT INTO bags (character_id, item_id, qty) VALUES (?, ?, 1)', [req.params.id, oldItemId]);
        }
    }
    // 获取最新属性、背包、装备栏
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    const [bag] = await conn.execute('SELECT b.id as bag_id, i.id as item_id, i.name, i.desc, i.type, i.rarity, b.qty FROM bags b JOIN items i ON b.item_id = i.id WHERE b.character_id = ?', [req.params.id]);
    const [equips] = await conn.execute('SELECT ce.slot, ce.item_id, i.name, i.desc, i.type, i.rarity, i.attack_bonus, i.defense_bonus, i.hp_bonus FROM character_equipments ce LEFT JOIN items i ON ce.item_id = i.id WHERE ce.character_id = ?', [req.params.id]);
    // 计算装备加成
    let equip_bonus = { atk: 0, def: 0, hp: 0 };
    for (const row of equips) {
        if (!row) continue;
        equip_bonus.atk += row.attack_bonus || 0;
        equip_bonus.def += row.defense_bonus || 0;
        equip_bonus.hp += row.hp_bonus || 0;
    }
    const base = {
        hp: charRows[0].hp,
        mp: charRows[0].mp,
        atk: charRows[0].atk,
        def: charRows[0].def
    };
    const final = {
        hp: base.hp + equip_bonus.hp,
        mp: base.mp,
        atk: base.atk + equip_bonus.atk,
        def: base.def + equip_bonus.def
    };
    await conn.end();
    res.json({ success: true, bag, equips, attributes: { base, equip_bonus, final } });
});

// 卸下装备
app.post('/api/characters/:id/unequip', async (req, res) => {
    const { slot } = req.body;
    const conn = await getConn();
    // 查找原装备
    const [equipRows] = await conn.execute('SELECT * FROM character_equipments WHERE character_id=? AND slot=?', [req.params.id, slot]);
    if (!equipRows.length || !equipRows[0].item_id) { await conn.end(); return res.status(400).json({ error: '该槽位无装备' }); }
    const oldItemId = equipRows[0].item_id;
    // 清空装备栏
    await conn.execute('UPDATE character_equipments SET item_id=NULL WHERE character_id=? AND slot=?', [req.params.id, slot]);
    // 装备回到背包
    const [oldBag] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, oldItemId]);
    if (oldBag.length) {
        await conn.execute('UPDATE bags SET qty=qty+1 WHERE id=?', [oldBag[0].id]);
    } else {
        await conn.execute('INSERT INTO bags (character_id, item_id, qty) VALUES (?, ?, 1)', [req.params.id, oldItemId]);
    }
    // 获取最新属性、背包、装备栏
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    const [bag] = await conn.execute('SELECT b.id as bag_id, i.id as item_id, i.name, i.desc, i.type, i.rarity, b.qty FROM bags b JOIN items i ON b.item_id = i.id WHERE b.character_id = ?', [req.params.id]);
    const [equips] = await conn.execute('SELECT ce.slot, ce.item_id, i.name, i.desc, i.type, i.rarity, i.attack_bonus, i.defense_bonus, i.hp_bonus FROM character_equipments ce LEFT JOIN items i ON ce.item_id = i.id WHERE ce.character_id = ?', [req.params.id]);
    // 计算装备加成
    let equip_bonus = { atk: 0, def: 0, hp: 0 };
    for (const row of equips) {
        if (!row) continue;
        equip_bonus.atk += row.attack_bonus || 0;
        equip_bonus.def += row.defense_bonus || 0;
        equip_bonus.hp += row.hp_bonus || 0;
    }
    const base = {
        hp: charRows[0].hp,
        mp: charRows[0].mp,
        atk: charRows[0].atk,
        def: charRows[0].def
    };
    const final = {
        hp: base.hp + equip_bonus.hp,
        mp: base.mp,
        atk: base.atk + equip_bonus.atk,
        def: base.def + equip_bonus.def
    };
    await conn.end();
    res.json({ success: true, bag, equips, attributes: { base, equip_bonus, final } });
});

// 获取角色周围物品
app.get('/api/characters/:id/env', async (req, res) => {
    const conn = await getConn();
    const [rows] = await conn.execute(`
        SELECT e.id as env_id, i.id as item_id, i.name, i.desc, i.type, i.rarity, e.qty
        FROM env_items e
        JOIN items i ON e.item_id = i.id
        WHERE e.character_id = ?
    `, [req.params.id]);
    await conn.end();
    res.json(rows);
});
// 拾取周围物品到背包
app.post('/api/characters/:id/env/pick', async (req, res) => {
    const { envId } = req.body;
    const conn = await getConn();
    // 查找env_items
    const [envRows] = await conn.execute('SELECT * FROM env_items WHERE id=? AND character_id=?', [envId, req.params.id]);
    if (!envRows.length) { await conn.end(); return res.status(404).json({ error: '物品不存在' }); }
    const envItem = envRows[0];
    // 背包合并
    const [bagRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, envItem.item_id]);
    if (bagRows.length) {
        await conn.execute('UPDATE bags SET qty=qty+? WHERE id=?', [envItem.qty, bagRows[0].id]);
    } else {
        await conn.execute('INSERT INTO bags (character_id, item_id, qty) VALUES (?, ?, ?)', [req.params.id, envItem.item_id, envItem.qty]);
    }
    // 删除env_items
    await conn.execute('DELETE FROM env_items WHERE id=?', [envId]);
    await conn.end();
    res.json({ success: true });
});
// 丢弃物品到周围
app.post('/api/characters/:id/env/drop', async (req, res) => {
    const { itemId, qty } = req.body;
    const conn = await getConn();
    // 背包扣除
    const [bagRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (!bagRows.length || bagRows[0].qty < qty) { await conn.end(); return res.status(400).json({ error: '背包数量不足' }); }
    if (bagRows[0].qty === qty) {
        await conn.execute('DELETE FROM bags WHERE id=?', [bagRows[0].id]);
    } else {
        await conn.execute('UPDATE bags SET qty=qty-? WHERE id=?', [qty, bagRows[0].id]);
    }
    // env_items合并
    const [envRows] = await conn.execute('SELECT * FROM env_items WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (envRows.length) {
        await conn.execute('UPDATE env_items SET qty=qty+? WHERE id=?', [qty, envRows[0].id]);
    } else {
        await conn.execute('INSERT INTO env_items (character_id, item_id, qty) VALUES (?, ?, ?)', [req.params.id, itemId, qty]);
    }
    await conn.end();
    res.json({ success: true });
});
// 刷新/生成周围物品（如打怪掉落）
app.post('/api/characters/:id/env/spawn', async (req, res) => {
    const { itemId, qty } = req.body;
    const conn = await getConn();
    // env_items合并
    const [envRows] = await conn.execute('SELECT * FROM env_items WHERE character_id=? AND item_id=?', [req.params.id, itemId]);
    if (envRows.length) {
        await conn.execute('UPDATE env_items SET qty=qty+? WHERE id=?', [qty, envRows[0].id]);
    } else {
        await conn.execute('INSERT INTO env_items (character_id, item_id, qty) VALUES (?, ?, ?)', [req.params.id, itemId, qty]);
    }
    await conn.end();
    res.json({ success: true });
});

// 金币商城购买物品
app.post('/api/characters/:id/shop/buy', async (req, res) => {
    const { itemId, qty } = req.body;
    const conn = await getConn();
    // 购买数量校验
    if (!Number.isInteger(qty) || qty < 1) { await conn.end(); return res.status(400).json({ error: '购买数量非法' }); }
    // 获取角色
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [req.params.id]);
    if (!charRows.length) { await conn.end(); return res.status(404).json({ error: '角色不存在' }); }
    const character = charRows[0];
    // 获取物品
    const [itemRows] = await conn.execute('SELECT * FROM items WHERE id=?', [itemId]);
    if (!itemRows.length) { await conn.end(); return res.status(404).json({ error: '物品不存在' }); }
    const item = itemRows[0];
    // 价格健壮性
    let price = Number(item.price);
    if (!price) price = 10 * (item.rarity || 1);
    const totalCost = price * qty;
    if ((character.coin || 0) < totalCost) { await conn.end(); return res.status(400).json({ error: '金币不足' }); }
    // 扣金币
    await conn.execute('UPDATE characters SET coin=coin-? WHERE id=?', [totalCost, character.id]);
    // 背包加物品
    const [existRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [character.id, itemId]);
    if (existRows.length) {
        await conn.execute('UPDATE bags SET qty=qty+? WHERE id=?', [qty, existRows[0].id]);
    } else {
        await conn.execute('INSERT INTO bags (character_id, item_id, qty) VALUES (?, ?, ?)', [character.id, itemId, qty]);
    }
    // 返回新金币数和背包，并返回本次购买物品信息
    const [charRows2] = await conn.execute('SELECT coin FROM characters WHERE id=?', [character.id]);
    const [bag] = await conn.execute('SELECT b.id as bag_id, i.id as item_id, i.name, i.desc, i.type, i.rarity, b.qty FROM bags b JOIN items i ON b.item_id = i.id WHERE b.character_id = ?', [character.id]);
    await conn.end();
    res.json({ success: true, coin: charRows2[0].coin, bag, bought: { id: item.id, name: item.name, qty, price, totalCost } });
});

const itemUseRouter = require('./item_use');
app.use(itemUseRouter);

const PORT = 3001;
app.listen(PORT, () => {
    console.log('Backend API running at http://localhost:' + PORT);
});